<?php
/**
 * @desc 微信.现金红包
 * @document https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_4&index=3
 * @author Vincent
 */

namespace young\payment;

use young\Common;

class WxMchRed extends WxConfig
{
    public function run($data)
    {
        $this->setConfig($data['config']);
        //desc [send_name=红包发送者名称,wishing=红包祝福语,act_name=活动名称,remark=备注信息]
        return $this->handle($data['desc'], $data['order_sn'], $data['amount'], $data['openid']);
    }

    public function handle($desc, $orderSn, $amount, $openid)
    {
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack';
        $common = [];
        $common['wxappid'] = $this->appid;
        $common['mch_id'] = $this->mch_id;
        $common['nonce_str'] = Common::rand_string(32);
        $common['send_name'] = $desc['send_name'];
        $common['mch_billno'] = $orderSn;
        $common['total_amount'] = $this->formatAmount($amount);
        $common['client_ip'] = $_SERVER['REMOTE_ADDR'];
        $common['re_openid'] = $openid;
        $common['total_num'] = 1;
        $common['wishing'] = $desc['wishing'];
        $common['act_name'] = $desc['act_name'];
        $common['remark'] = $desc['remark'];
        $common['sign'] = $this->sign($common);
        $xml = Common::arrayToXml($common);
        $result = $this->request_post($url, $xml);
        $result = Common::xmlToArray($result);
        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            return true;
        } else {
            throw new \Exception('[code:' . $result['return_code'] . '][msg:' . $result['return_msg'] . '][err_code_des:' . $result['err_code_des'] . ']');
        }
    }
}